package 集合到文件数据排序改进;


import java.io.*;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

public class ArrayListToTxtDemo {
    public static void main(String[] args) throws IOException {
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {//使用比较器排序进行排序
            @Override
            public int compare(Student s1, Student s2) {
                //分数从高到低
                int num = s2.getSum() - s1.getSum();
                //次要条件
                int num2 = num == 0 ? s2.getChinesescore() - s1.getChinesescore() : num;//将语文成绩进行比较
                int num3 = num == 0 ? s2.getEnglishscore() - s1.getEnglishscore() : num2;//将英语成绩进行比较
                int num4 = num3 == 0 ? s1.getName().compareTo(s1.getName()) : num3;//将名字进行比较

                return num4;
            }
        });
        //键盘录入学生数据
        for (int i = 0; i < 5; i++) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请录入数据" + (i + 1) + "个学生信息：");
            System.out.println("姓名：");
            String name = sc.nextLine();
            System.out.println("语文成绩：");
            int chinesescore = sc.nextInt();
            System.out.println("数学成绩：");
            int mathscore = sc.nextInt();
            System.out.println("英语成绩");
            int englishscore = sc.nextInt();
            //创建学生对象，把键盘录入的数据对应赋值给学生对象的成员变量
            Student s = new Student();
            s.setName(name);
            s.setChinesescore(chinesescore);
            s.setMathscore(mathscore);
            s.setEnglishscore(englishscore);

            //把学生对象添加到TreeSet集合
            ts.add(s);
        }
        //创建字符缓冲输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("222.txt"));

        //遍历集合，得到每一个学生对象
        for (Student s : ts) {
            //把学生对象拼接成指定的字符串
            StringBuilder sb = new StringBuilder();
            sb.append(s.getName()).append(",").append(s.getChinesescore()).append(",").append(s.getMathscore()).append(",").append(s.getEnglishscore()).append(",").append(s.getSum());

            //调用字符缓冲输出流的方法写数据
            bw.write(sb.toString());
            bw.newLine();
            bw.flush();

        }
        bw.close();
    }
}
